package com.pubinfo.passbook.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.pubinfo.passbook.common.config.ApplicationConfig;
import com.pubinfo.passbook.common.entity.TPassbook;
import com.pubinfo.passbook.common.entity.TWiteoffInstance;
import com.pubinfo.passbook.common.mapper.TSourceArtificialMapper;
import com.pubinfo.passbook.common.mapper.TSourcePassbookMapper;
import com.pubinfo.passbook.common.mapper.TWiteoffInstanceMapper;
import com.pubinfo.passbook.common.model.http.baseEntity.BaseBody;
import com.pubinfo.passbook.common.model.http.baseEntity.Baseinfo;
import com.pubinfo.passbook.common.model.http.baseEntity.Message;
import com.pubinfo.passbook.common.model.http.baseEntity.request.IRequest;
import com.pubinfo.passbook.common.model.http.baseEntity.request.MessageList;
import com.pubinfo.passbook.common.model.http.baseEntity.request.RequestEnvelope;
import com.pubinfo.passbook.common.model.http.request.GainWriteoffInstStatus.GainWriteoffInstStatusBody;
import com.pubinfo.passbook.common.model.http.request.GainWriteoffInstStatus.GainWriteoffInstStatusItems;
import com.pubinfo.passbook.common.model.http.response.GetWriteoffInstStatus.WriteoffInstStatusEnvelope;
import com.pubinfo.passbook.common.model.http.response.GetWriteoffInstStatus.WriteoffInstStatusItem;
import com.pubinfo.passbook.common.model.http.response.GetWriteoffInstStatus.WriteoffInstStatusMessage;
import com.pubinfo.passbook.common.service.master.TPassbookService;
import com.pubinfo.passbook.common.service.mss.HttpService;
import com.pubinfo.passbook.common.service.uccp.UccpService;
import com.pubinfo.passbook.data.service.MssService;
import com.pubinfo.passbook.data.service.OpenWiteoffService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MssServiceImpl implements MssService {
  @Autowired
  TWiteoffInstanceMapper instanceMapper;
  @Autowired
  TSourcePassbookMapper passbookMapper;
  @Autowired
  UccpService uccpService;
  @Resource
  ApplicationConfig config;
  @Autowired
  TPassbookService passbookService;
  @Autowired
  TSourceArtificialMapper artificialMapper;
  @Autowired
  HttpService httpService;
  @Autowired
  OpenWiteoffService openWiteoffService;
  
  @SneakyThrows
  @Override
  public WriteoffInstStatusMessage getWriteoffInstStatusBodyItem(List<GainWriteoffInstStatusItems> account) {
    System.out.println(config);
    String postUrl = config.getEsb().getUrl() + config.getEsb().getApi().getGainWriteoffInstStatus();
    BaseBody baseBody = new BaseBody();
    Message message = new Message(new MessageList(account));
    baseBody.setBaseinfo(Baseinfo.createBaseinfo("gainWriteoffInstStatus", new Date()));
    baseBody.setMessage(message);
    RequestEnvelope requestEnvelope = new RequestEnvelope();
    GainWriteoffInstStatusBody body = new GainWriteoffInstStatusBody();
    IRequest IRequest = new IRequest();
    IRequest.setBaseBody(baseBody);
    body.setIRequest(IRequest);
    requestEnvelope.setRequestBody(body);
    //发送post请求
    String s = sendPost(new XmlMapper().writeValueAsString(requestEnvelope), postUrl);
    //处理&#60;和&#62;的乱码
    s = s.replaceAll("&#60;", "<").replaceAll("&#62;", ">");
    System.out.println(s);
    WriteoffInstStatusEnvelope writeoffInstStatusEnvelope = new XmlMapper().readValue(s, WriteoffInstStatusEnvelope.class);
    WriteoffInstStatusMessage writeoffInstStatusBodyMessage = new XmlMapper().readValue(writeoffInstStatusEnvelope.getBody().getEResponse().getBaseBody().getMessage().getMessage(), WriteoffInstStatusMessage.class);
    
    return writeoffInstStatusBodyMessage;
  }
  
  @SneakyThrows
  @Override
  public String sendPost(String xml, String url) {
    ////Unirest.setTimeouts(0, 0);
    HttpResponse<String> response = Unirest.post(url)
        .header("Authorization", config.getEsb().getAuthorization())
        .header("User-Agent", "apifox/1.0.0")
        .header("Content-Type", "application/xml").body(xml)
        .asString();
    return response.getBody();
  }
  
  @Override
  public void getWriteoffInstStatus() {
    List<TWiteoffInstance> tWiteoffInstances = instanceMapper.selectStatusNotReady();
    for (TWiteoffInstance tWiteoffInstance : tWiteoffInstances) {
      List<GainWriteoffInstStatusItems> list = new ArrayList<>();
      list.add(new GainWriteoffInstStatusItems(tWiteoffInstance.getOtherSystemMainId()));
      WriteoffInstStatusMessage writeoffInstStatusMessage = getWriteoffInstStatusBodyItem(list);
      if (!CollectionUtils.isEmpty(writeoffInstStatusMessage.getItems())) {
        WriteoffInstStatusItem instStatus = writeoffInstStatusMessage.getItems().get(0);
        UpdateWrapper<TWiteoffInstance> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", tWiteoffInstance.getId());
        updateWrapper.set("witeoff_Instance_code", instStatus.getWriteoffInstanceCode());
        updateWrapper.set("status", instStatus.getStatus());
        updateWrapper.set("sap_certificate_code", instStatus.getSapCertificateCode());
        updateWrapper.set("year", instStatus.getYear());
        updateWrapper.set("sap_creator", instStatus.getSapCreator());
        updateWrapper.set("account_code", instStatus.getAccountCode());
        updateWrapper.set("abstract_", instStatus.getAbstract_());
        updateWrapper.set("audit_sum", instStatus.getAuditSum());
        updateWrapper.set("act_name", instStatus.getActName());
        updateWrapper.set("handler_account", instStatus.getHandlerAccount());
        instanceMapper.update(null, updateWrapper);
        log.info(tWiteoffInstance.getId() + "状态已更新");
        //在 -1 -2状态时对票据取消锁定  findPassbookByWiteoffId
        if ("-1".equals(instStatus.getStatus()) || "-2".equals(instStatus.getStatus()) || "-3".equals(instStatus.getStatus())) {
          List<TPassbook> passbookList = passbookMapper.findPassbookByWiteoffId(tWiteoffInstance.getId());
          if (!CollectionUtils.isEmpty(passbookList)) {
            passbookList.stream().forEach(tPassbook -> {
              tPassbook.setSystemIsLocked("N");
            });
            passbookService.saveOrUpdateBatch(passbookList);
          }
          // 将单据解锁
          artificialMapper.updateByWiteoffId(tWiteoffInstance.getId());
          //将票据解锁
          passbookMapper.updateSystemIsLocked(tWiteoffInstance.getOtherSystemMainId());
          //再次根据报账单发起一次报账，但是这次报账走待办
          httpService.createWriteoffAgain(tWiteoffInstance);
        }
      }
    }
    
    List<TWiteoffInstance> witeoffInstances = instanceMapper.selectNeedSendShortMessage();
    
    Map<String, List<TWiteoffInstance>> witeoffInstanceMap = witeoffInstances.stream().collect(Collectors.groupingBy(TWiteoffInstance::getIdNo));
    for (String idNo : witeoffInstanceMap.keySet()) {
      List<String> witeoffids = new ArrayList<>();
      witeoffInstanceMap.get(idNo).stream().forEach(TWiteoffInstance -> witeoffids.add(TWiteoffInstance.getId()));
      if(uccpService.sendShortMessage(witeoffids, idNo))
      {
        instanceMapper.updateIsNeedImage(witeoffids);
      }
    }
  }

  @Override
  public void getOpenWriteoffInstStatus() {
    List<TWiteoffInstance> tWiteoffInstances = instanceMapper.selectOpenStatusNotReady();
    for (TWiteoffInstance tWiteoffInstance : tWiteoffInstances) {
      WriteoffInstStatusMessage writeoffInstStatusMessage = openWiteoffService.getWriteoffInstStatus(new GainWriteoffInstStatusItems(tWiteoffInstance.getOtherSystemMainId()), tWiteoffInstance.getSystemCode());
      if (!CollectionUtils.isEmpty(writeoffInstStatusMessage.getItems())) {
        WriteoffInstStatusItem instStatus = writeoffInstStatusMessage.getItems().get(0);
        UpdateWrapper<TWiteoffInstance> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", tWiteoffInstance.getId());
        updateWrapper.set("witeoff_Instance_code", instStatus.getWriteoffInstanceCode());
        updateWrapper.set("status", instStatus.getStatus());
        updateWrapper.set("sap_certificate_code", instStatus.getSapCertificateCode());
        updateWrapper.set("year", instStatus.getYear());
        updateWrapper.set("sap_creator", instStatus.getSapCreator());
        updateWrapper.set("account_code", instStatus.getAccountCode());
        updateWrapper.set("abstract_", instStatus.getAbstract_());
        updateWrapper.set("audit_sum", instStatus.getAuditSum());
        updateWrapper.set("act_name", instStatus.getActName());
        updateWrapper.set("handler_account", instStatus.getHandlerAccount());
        instanceMapper.update(null, updateWrapper);
        log.info(tWiteoffInstance.getId() + "状态已更新");
        //在 -1 -2状态时对票据取消锁定  findPassbookByWiteoffId
        if ("-1".equals(instStatus.getStatus()) || "-2".equals(instStatus.getStatus()) || "-3".equals(instStatus.getStatus())) {
          List<TPassbook> passbookList = passbookMapper.findPassbookByWiteoffId(tWiteoffInstance.getId());
          if (!CollectionUtils.isEmpty(passbookList)) {
            passbookList.stream().forEach(tPassbook -> {
              tPassbook.setSystemIsLocked("N");
            });
            passbookService.saveOrUpdateBatch(passbookList);
          }
          // 将单据解锁
          artificialMapper.updateByWiteoffId(tWiteoffInstance.getId());
          //将票据解锁
          passbookMapper.updateSystemIsLocked(tWiteoffInstance.getOtherSystemMainId());
        }
      }
    }
  }
}
